package com.example.demopublish.controller;

import com.example.demopublish.config.JwTokenConfig;
import com.example.demopublish.dto.ResponseData;
import com.example.demopublish.dto.TokenDto;
import com.example.demopublish.dto.UserDto;
import com.example.demopublish.entity.JwUser;
import com.example.demopublish.service.impl.JwUserServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class LoginController {
    @Autowired
    private JwUserServiceImpl jwUserService;
    @Autowired
    private JwTokenConfig jwTokenConfig;

    @PostMapping(value = "/login")
    public ResponseData login(@RequestBody UserDto userDto) {

        if (ObjectUtils.isEmpty(userDto)
                || StringUtils.isEmpty(userDto.getUsername())
                || StringUtils.isEmpty(userDto.getPassword())
        ) {
            return ResponseData.error("用户名或密码不能为空");
        }

        List<JwUser> resultList = jwUserService.getOneByWrapper(userDto);
        if (CollectionUtils.isEmpty(resultList)) {
            return ResponseData.error("用户名或密码错误");
        }
        JwUser jwUser = resultList.get(0);
        String token = jwTokenConfig.generateToken(jwUser.getName());
        Long expireTime = jwTokenConfig.getExpireTime(token, jwTokenConfig.getSecret());
        TokenDto tokenDto = new TokenDto();
        tokenDto.setToken(token);
        tokenDto.setExpire(expireTime);
        tokenDto.setUsername(jwUser.getName());
        return ResponseData.ok(tokenDto);
    }

    @GetMapping(value = "/info")
    public ResponseData info(@RequestParam(value = "token")String token) {
        HashMap<String, Object> param = new HashMap<>();
        String username = jwTokenConfig.getUsernameFromToken(token);
        param.put("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        param.put("name",username);
        return ResponseData.ok(param);
    }


    @PostMapping(value = "/logout")
    public ResponseData logout() {
        return ResponseData.ok();
    }
    @PostMapping(value = "/logout1")
    public ResponseData logout1() {
        return ResponseData.ok("KEYRUS IS GARBAGE!");
    }
    @PostMapping(value = "/logout2")
    public ResponseData logout2() {
        return ResponseData.ok("jwjw!");
    }


}
